window.onload = function () {
  fetchCourseList();  // 页面加载时获取课程数据
};

const logoutBtn = document.getElementById("logout-btn");
let currentUnitId = null; // 当前操作的学习单元ID，新增时为null

// 获取课程列表
function fetchCourseList() {
  fetch('http://localhost:8083/api/teacher/course/list', {  // 后端课程列表接口
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      pageNum: 1,  // 当前页码
      pageSize: 10  // 每页数据量
    })
  })
  .then(response => response.json())
  .then(data => {
    if (data.code === 200) {
      renderCourseList(data.data.records);  // 假设后端返回的数据结构为：data.data.records
    } else {
      alert('获取课程数据失败');
    }
  })
  .catch(error => {
    console.error('Error fetching courses:', error);
    alert('获取课程数据失败');
  });
}

// 渲染课程数据到表格
function renderCourseList(courses) {
  const tableBody = document.getElementById("courseTableBody");
  tableBody.innerHTML = '';  // 清空表格内容
  courses.forEach(course => {
    const row = document.createElement("tr");
    row.id = `course-${course.id}`; // 给每行一个唯一ID
    row.innerHTML = `
      <td>${course.id}</td>
      <td>${course.name}</td>
      <td>${course.status}</td>
      <td>
        <button onclick="viewStudents(${course.id})">查看学生</button>
        <button onclick="editCourse(${course.id})">编辑</button>
        <button onclick="deleteCourse(${course.id})">删除</button>
      </td>
    `;
    tableBody.appendChild(row);
  });
}

// 查看学生列表
function viewStudents(courseId) {
  fetch(`http://localhost:8083/api/teacher/course/${courseId}/students`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      pageNum: 1,
      pageSize: 10
    })
  })
  .then(response => response.json())
  .then(data => {
    if (data.code === 200) {
      renderStudents(data.data.records);
    } else {
      alert('获取学生数据失败');
    }
  })
  .catch(error => {
    console.error('Error fetching students:', error);
    alert('获取学生数据失败');
  });
}

// 渲染学生数据到表格
function renderStudents(students) {
  const tableBody = document.getElementById("studentTableBody");
  tableBody.innerHTML = '';  // 清空表格内容
  students.forEach(student => {
    const row = document.createElement("tr");
    row.innerHTML = `
      <td>${student.id}</td>
      <td>${student.name}</td>
      <td>${student.progress}</td>
    `;
    tableBody.appendChild(row);
  });
}

// 编辑课程
function editCourse(courseId) {
  openCourseModal('edit', courseId);
}

// 打开课程编辑弹窗
function openCourseModal(action, courseId = null) {
  const modal = document.getElementById("course-modal");
  const modalTitle = document.getElementById("modal-title");
  const saveBtn = document.getElementById("save-course-btn");

  if (action === 'create') {
    modalTitle.textContent = "新增课程";
    saveBtn.textContent = "保存";
    currentCourseId = null;
    clearCourseModalFields();
  } else if (action === 'edit') {
    modalTitle.textContent = "编辑课程";
    saveBtn.textContent = "保存修改";
    currentCourseId = courseId;

    // 获取课程数据并填充到输入框中
    fetch(`http://localhost:8083/api/teacher/course/${courseId}`)
      .then(response => response.json())
      .then(data => {
        if (data.code === 200) {
          const course = data.data;
          document.getElementById("course-name").value = course.name;
          document.getElementById("course-status").value = course.status;
        } else {
          alert('获取课程数据失败');
        }
      })
      .catch(error => {
        console.error('Error fetching course:', error);
        alert('获取课程数据失败');
      });
  }

  modal.style.display = "block"; // 打开弹窗
}

// 清空课程弹窗中的输入字段
function clearCourseModalFields() {
  document.getElementById("course-name").value = "";
  document.getElementById("course-status").value = "open"; // 默认选择“已开启”
}

// 关闭课程弹窗
function closeCourseModal() {
  const modal = document.getElementById("course-modal");
  modal.style.display = "none";
}

// 保存课程数据
document.getElementById("course-form").addEventListener("submit", function (event) {
  event.preventDefault();

  const courseName = document.getElementById("course-name").value.trim();
  const courseStatus = document.getElementById("course-status").value.trim();

  if (courseName === "" || courseStatus === "") {
    alert("请输入所有课程信息");
    return;
  }

  const courseDTO = {
    name: courseName,
    status: courseStatus
  };

  if (currentCourseId === null) {
    // 新增课程
    fetch('http://localhost:8083/api/teacher/course/add', {  // 新增课程接口
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(courseDTO)
    })
    .then(response => response.json())
    .then(data => {
      if (data.code === 200) {
        fetchCourseList();  // 重新获取课程列表
        closeCourseModal();
      } else {
        alert('新增课程失败');
      }
    })
    .catch(error => {
      console.error('Error adding course:', error);
      alert('新增课程失败');
    });
  } else {
    // 编辑课程
    courseDTO.id = currentCourseId;
    fetch('http://localhost:8083/api/teacher/course/update', {  // 编辑课程接口
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(courseDTO)
    })
    .then(response => response.json())
    .then(data => {
      if (data.code === 200) {
        fetchCourseList();  // 重新获取课程列表
        closeCourseModal();
      } else {
        alert('编辑课程失败');
      }
    })
    .catch(error => {
      console.error('Error editing course:', error);
      alert('编辑课程失败');
    });
  }
});

// 删除课程
function deleteCourse(courseId) {
  fetch(`http://localhost:8083/api/teacher/course/delete/${courseId}`, {  // 删除课程接口
    method: 'POST',
  })
  .then(response => response.json())
  .then(data => {
    if (data.code === 200) {
      fetchCourseList();  // 重新获取课程列表
    } else {
      alert('删除课程失败');
    }
  })
  .catch(error => {
    console.error('Error deleting course:', error);
    alert('删除课程失败');
  });
}

// 退出按钮点击事件
logoutBtn.addEventListener('click', () => {
  window.location.href = '../login.html'; // 假设你要跳转到登录页面
});
